/**************************************************************************************************
 * light library                                                                                  *
 * Copyright © 2012 David Kretzmer                                                                *
 *                                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software  *
 * and associated documentation files (the "Software"), to deal in the Software without           *
 * restriction,including without limitation the rights to use, copy, modify, merge, publish,      *
 * distribute,sublicense, and/or sell copies of the Software, and to permit persons to whom the   *
 * Software is furnished to do so, subject to the following conditions:                           *
 *                                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies or       *
 * substantial portions of the Software.                                                          *
 *                                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING  *
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND     *
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.        *
 *                                                                                                *
 *************************************************************************************************/

#include "light/light.hpp"

#ifdef LIGHT_PLATFORM_LINUX

#include "light/io/internal/linux_file.hpp"
#include "light/diagnostics/errors.hpp"
#include "light/utility/safe_int_cast.hpp"

#ifndef _LARGEFILE64_SOURCE
	#define _LARGEFILE64_SOURCE // Make 'lseek64' available which uses 64-bit instead of 32-bit types
#endif
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>


namespace light
{
namespace io
{
namespace internal
{
	namespace
	{
		int access_to_impl(access acc)
		{
			int res = 0;
			if(acc & access::read)
			{
				if(acc & access::write)
					res |= O_RDWR |
						   O_CREAT; // Create new file if it doesn't already exist
				else
					res |= O_RDONLY;
			}
			else if(acc & access::write)
				res |= O_WRONLY |
					   O_CREAT; // Create new file if it doesn't already exist

			if(acc & access::append)
				res |= O_APPEND;
			if(acc & access::trunc)
				res |= O_TRUNC;

			return res;
		}
	}

	// Constructor. Opens a file
	file_base::file_base(utf8_unit const *filename, access acc)
	{
		open(filename, acc);
	}

	// Destructor. Closes the file
	file_base::~file_base()
	{
		close();
	}

	// Opens a file
	void file_base::open(utf8_unit const *filename, access acc)
	{
		int flags = access_to_impl(acc);
		if(flags & O_CREAT)
			m_descriptor = ::open64(filename, flags,                        // open64: adds support for large file sizes
									S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); // Create new file with standard permissions
		else
			m_descriptor = ::open64(filename, flags);

		if(m_descriptor == -1)
			throw ::std::runtime_error("cannot open file");
	}

	// Closes the file
	void file_base::close()
	{
		if(descriptor() != -1)
		{
			int file_close_result = ::close(descriptor());
			assert(file_close_result == 0);
			m_descriptor = -1;
		}

	}

	// Writes 'num_bytes' from 'data' to the file. Returns the number of bytes actually written
	size_t file_base::write(void const *data, size_t num_bytes)
	{
		ssize_t res = ::write(descriptor(), data, num_bytes);
		if(res == -1)
			throw runtime_error("cannot write to file");

		return res;
	}

	// Reads 'num_bytes' from the file to 'data'. Returns the number of bytes actually read
	size_t file_base::read(void *data, size_t num_bytes)
	{
		ssize_t res = ::read(descriptor(), data, num_bytes);
		if(res == -1)
			throw runtime_error("cannot write to file");

		return res;
	}


	namespace
	{
		int seek_to_impl(seek_pos pos)
		{
			return pos == seek_pos::begin ? SEEK_SET :
				   pos == seek_pos::relative ? SEEK_CUR : SEEK_END;
		}
	}


	// Sets the read/write offset relative from 'pos'. Returns the offset from the beginning of the file
	uint8 file_base::seek(uint8 offset, seek_pos pos)
	{
		off64_t abs = lseek64(descriptor(), static_cast<off64_t>(offset), seek_to_impl(pos));
		if(abs == -1)
			throw runtime_error("cannot seek to specified position");

		return static_cast<uint8>(abs);
	}

	// Gets the current read/write offset
	uint8 file_base::tell() const
	{
		off64_t abs = lseek64(descriptor(), 0, SEEK_CUR);
		if(abs == -1)
			throw runtime_error("cannot seek to specified position");

		return static_cast<uint8>(abs);
	}

	// Gets the size of the file
	uint8 file_base::size() const
	{
		off64_t old_pos = lseek64(descriptor(), 0, SEEK_CUR);
		off64_t end = lseek64(descriptor(), 0, SEEK_END);
		lseek64(descriptor(), old_pos, SEEK_SET);

		return static_cast<uint8>(end);
	}


} // namespace: internal
} // namespace: io
} // namespace: light


#endif // conditional compilation: LIGHT_PLATFORM_LINUX
